<?php


namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\model\CustomerFavorite;
use app\common\customer\validate\CustomerFavoriteValidate;
use think\db\exception\DbException;

class Favorite extends Api
{
    public function doFav()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        // 必须字段验证
        $validate = new CustomerFavoriteValidate();
        if (!$validate->check($post)) return error([], $validate->getError());

        // 查询是否有该客资

        $model = new CustomerFavorite();
        $where = [];
        $where['member_id'] = $post['member_id'];
        $where['user_id'] = $user['id'];
        $where['type'] = $post['type'];

        $row = $model->where($where)->find();
        if ($post['status'] == 1) { // 关注
            if (!empty($row)) {
                return error([], "请勿重复操作或刷新页面");
            } else {
                try {
                    $model->save($where);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
        } else { // 取关
            $row->delete(true);
        }

        $result = [];
        $where = [];
        $where['member_id'] = $post['member_id'];
        $where['user_id'] = $user['id'];
        $fields = 'member_id,user_id,type';
        $result['favorites'] = $model->where($where)->field($fields)->select();
        return success($result, "操作成功");
    }
}